package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pojo.Book;
import pojo.User;
import service.BookManager;
import service.impl.BookManagerFactory;
public class HomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BookManager bookManager;
       
    public HomeServlet() {
        super();
        bookManager = BookManagerFactory.getInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		User u = (User) session.getAttribute("user");
		System.out.println("home sevlet get the user--"+u);
		
		List<Book> books = bookManager.findAll();
		for (Book book : books) {
			System.out.println(book.getId());
		}
		if(!books.isEmpty()){
			Map<String, Integer> bNum = (Map<String, Integer>) session.getAttribute("bnum");
			if(bNum==null){
				bNum = new HashMap<String, Integer>();
				for(int i=0; i<books.size(); i++){
					bNum.put(books.get(i).getId(), 0);
				}
			}
			
			session.setAttribute("bnum", bNum);
			session.setAttribute("books", books);
			response.sendRedirect("home.jsp");
		}else{
			PrintWriter writer = response.getWriter();
			writer.write("Oops! Can not load books data!");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
